package com.example.choupaiapp.main.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.fragment.CommonFragment;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.view.TabEntity;
import com.example.choupaiapp.main.bean.MessageCountBean;
import com.example.choupaiapp.main.bean.MsgUser;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.fragment.message.ConversationListFragment;
import com.example.choupaiapp.main.fragment.message.NoticeFragment;
import com.example.choupaiapp.main.fragment.message.RemindFragment;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.flyco.tablayout.utils.UnreadMsgUtils;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by ASUS on 2019/10/30.
 */

public class MessageFragment extends CommonFragment {

    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.common_bottom_tab)
    CommonTabLayout commonBottomTab;
    Unbinder unbinder;

    private String[] mTitles = new String[3];
    private ArrayList<Fragment> mFragments = new ArrayList<>();//存放Fragment
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private ConversationListFragment privateLetterFragment;
    private UserInfoBean mUserInfoBean;
    private Map<String, EaseUser> contactList;

    public static MessageFragment newInstance() {
        return new MessageFragment();
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_message, container, false);
        unbinder = ButterKnife.bind(this, view);

        EventBus.getDefault().register(this);

        mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");

        mTitles[0] = "提醒";
        RemindFragment remindFragment = RemindFragment.newInstance();
        mFragments.add(remindFragment);

        mTitles[1] = "私信";
        privateLetterFragment = ConversationListFragment.newInstance();
        mFragments.add(privateLetterFragment);

        mTitles[2] = "通知";
        NoticeFragment noticeFragment = NoticeFragment.newInstance();
        mFragments.add(noticeFragment);

        commonBottomTab.setTextSelectColor(getResources().getColor(R.color.color_333));

        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i]));
        }

        viewpager.setAdapter(new MyPagerAdapter(getChildFragmentManager()));
        commonBottomTab.setTabData(mTabEntities);

        commonBottomTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewpager.setCurrentItem(position);
                if(position==0){
                    MobclickAgent.onEvent(ContextUtil.getContext(), "remindID");
                }else if(position==1){
                    MobclickAgent.onEvent(ContextUtil.getContext(), "directMessageID");
                }else if(position==2){
                    MobclickAgent.onEvent(ContextUtil.getContext(), "noticeID");
                }
//                UnreadMsgUtils.hide(commonBottomTab.getMsgView(position));
            }

            @Override
            public void onTabReselect(int position) {
//                UnreadMsgUtils.hide(commonBottomTab.getMsgView(position));
            }
        });

        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                commonBottomTab.setCurrentTab(position);
                if(position==0){
                    MobclickAgent.onEvent(ContextUtil.getContext(), "remindID");
                }else if(position==1){
                    privateLetterFragment.refresh();
                    MobclickAgent.onEvent(ContextUtil.getContext(), "directMessageID");
                }else if(position==2){
                    MobclickAgent.onEvent(ContextUtil.getContext(), "noticeID");
                }
//                UnreadMsgUtils.hide(commonBottomTab.getMsgView(position));
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }


        });

        viewpager.setCurrentItem(1);
        viewpager.setOffscreenPageLimit(3);

        return view;
    }

    private void refreshUIWithMessage() {
        context.runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                if (EMClient.getInstance().chatManager().getUnreadMessageCount() > 5) {
                    EventBus.getDefault().post("conversationListCount");
                }

                if (EMClient.getInstance().chatManager().getUnreadMessageCount() > 0) {
                    if (commonBottomTab != null) {
                        EventBus.getDefault().post("receive_msg");
                        UnreadMsgUtils.show(commonBottomTab.getMsgView(1), EMClient.getInstance().chatManager().getUnreadMessageCount());
                    }
                } else {
                    if (commonBottomTab != null) {
                        UnreadMsgUtils.hide(commonBottomTab.getMsgView(1));
                    }
                }

                privateLetterFragment.refresh();
            }
        });
    }


    EMMessageListener msgListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {

            if (contactList == null) {
                contactList = new Hashtable<String, EaseUser>();
            }

            for (EMMessage message : messages) {
                //接收并处理扩展消息
                String userName = message.getStringAttribute(Config.USER_NAME, "");
                String userPic = message.getStringAttribute(Config.USER_HEAD_PIC, "");
                String hxIdFrom = message.getFrom();
                Logger.e(userName + "**" + userPic + "**" + hxIdFrom);
                EaseUser easeUser = new EaseUser(hxIdFrom.toUpperCase());
                easeUser.setAvatar(userPic);
                easeUser.setNickname(userName);

                MsgUser msgUser = new MsgUser();
                msgUser.setUserName(userName);
                msgUser.setUserHead(userPic);
                SharedPreferencesHelp.putBean(hxIdFrom.toUpperCase(), msgUser);

                contactList.put(hxIdFrom, easeUser);
            }

            refreshUIWithMessage();

        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            //消息被撤回
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动
        }
    };

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initData() {

        EaseUI.getInstance().setUserProfileProvider(easeUserProfileProvider);


        EMClient.getInstance().chatManager().addMessageListener(msgListener);

        requestCount();
    }

    @Override
    public void onResume() {
        super.onResume();
        privateLetterFragment.refresh();
    }

    private void requestCount() {
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.MESSAGE_COUNT, null, Url.MESSAGE_COUNT, new Callback<MessageCountBean>() {
            @Override
            public void onSuccess(MessageCountBean messageCountBean) {
                if (messageCountBean.getCode() == Contacts.SUCCESS) {
                    if (messageCountBean.getSumRemind() != 0) {
                        UnreadMsgUtils.show(commonBottomTab.getMsgView(0), messageCountBean.getSumRemind());
                    } else {
                        UnreadMsgUtils.hide(commonBottomTab.getMsgView(0));
                    }

                    if (messageCountBean.getMessage() != 0) {
                        UnreadMsgUtils.show(commonBottomTab.getMsgView(2), messageCountBean.getMessage());
                    } else {
                        UnreadMsgUtils.hide(commonBottomTab.getMsgView(2));
                    }

                    EventBus.getDefault().post("remindCount:" + messageCountBean.getLike() + ":" + messageCountBean.getComment() + ":" + messageCountBean.getAttention());
                } else {
                    if (messageCountBean.getCode() == Contacts.TOKEN_EMPTY) {
                    }else{
                        showImageToas(messageCountBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
            }
        });
    }

    private EaseUI.EaseUserProfileProvider easeUserProfileProvider = new EaseUI.EaseUserProfileProvider() {
        @Override
        public EaseUser getUser(String username) {

            return getUserInfo(username);
        }
    };


    private EaseUser getUserInfo(String username) {
//        Logger.e("111111" + username+"***"+EMClient.getInstance().getCurrentUser());
        username = username.toUpperCase();
        //获取 EaseUser实例, 这里从内存中读取
        //如果你是从服务器中读读取到的，最好在本地进行缓存
        EaseUser user = null;
        //如果用户是本人，就设置自己的头像
        if (username.equalsIgnoreCase(EMClient.getInstance().getCurrentUser())) {
//            Logger.e("66666" + username+"***"+mUserInfoBean.getUser().getNickname());
            user = new EaseUser(username);
            user.setAvatar(mUserInfoBean.getUser().getAvatar());
            user.setNickname(mUserInfoBean.getUser().getNickname());
            return user;
        }
        //收到别人的消息，设置别人的头像
        if (contactList != null && contactList.containsKey(username)) {
            user = contactList.get(username);
        } else {
            MsgUser msgUser = (MsgUser) SharedPreferencesHelp.getBean(username);
            if (msgUser != null) {
//                Logger.e("2222" + msgUser.getUserName());
                user = new EaseUser(username);
                user.setAvatar(msgUser.getUserHead());
                user.setNickname(msgUser.getUserName());
//                contactList.put(username,user);
            }

        }

        //如果用户不是你的联系人，则进行初始化
        if (user == null) {
            user = new EaseUser(username);
            MsgUser msgUser = (MsgUser) SharedPreferencesHelp.getBean(username);
            if (msgUser != null) {
//                Logger.e("33333" + msgUser.getUserName());
                user.setAvatar(msgUser.getUserHead());
                user.setNickname(msgUser.getUserName());
//                contactList.put(username,user);
            }
            EaseCommonUtils.setUserInitialLetter(user);
        } else {
//            Logger.e("4444" + user.getNickname());
            if (TextUtils.isEmpty(user.getNickname())) {//如果名字为空，则显示环信号码
                user.setNickname(user.getUsername());
            }
        }
        EventBus.getDefault().post("receive_msg");
        return user;
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        if (event.equals("clearMessageRemind")) {
            requestCount();
        } else if (event.equals("conversationClear")) {
//            UnreadMsgUtils.hide(commonBottomTab.getMsgView(1));
            refreshUIWithMessage();
        }
    }
}
